package com.xu.cloud.shorturl.controller;

import com.xu.cloud.common.api.XuApiMethod;
import com.xu.cloud.common.pojo.Result;
import com.xu.cloud.shorturl.pojo.dto.UrlInfoDTO;
import com.xu.cloud.shorturl.pojo.http.BatchGenerateShortUrlReq;
import com.xu.cloud.shorturl.pojo.http.BatchGenerateShortUrlResp;
import com.xu.cloud.shorturl.pojo.http.GenerateShortUrlReq;
import com.xu.cloud.shorturl.pojo.http.GenerateShortUrlResp;
import com.xu.cloud.shorturl.service.ShortUrlService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author xuguan
 * @since 2024/3/5
 */
@RestController
@RequestMapping("/shortUrl/v1")
@Validated
@RequiredArgsConstructor
public class ShortUrlController {
    private final ShortUrlService shortUrlService;

    @XuApiMethod(apiCode = "XUSU0001", apiDesc = "生成短地址")
    @PostMapping("/generateShortUrl")
    public Result<GenerateShortUrlResp> generateShortUrl(@Valid @RequestBody GenerateShortUrlReq req) {
        final String shortUrl = shortUrlService.generateShortUrl(req.getOriginUrl());
        final GenerateShortUrlResp resp = new GenerateShortUrlResp();
        resp.setShortUrl(shortUrl);

        return Result.ok(resp);
    }

    @XuApiMethod(apiCode = "XUSU0002", apiDesc = "批量生成短地址")
    @PostMapping("/batchGenerateShortUrl")
    public Result<BatchGenerateShortUrlResp> batchGenerateShortUrl(@Valid @RequestBody BatchGenerateShortUrlReq req) {
        final List<UrlInfoDTO> urlInfoDTOs = shortUrlService.batchGenerateShortUrl(req.getOriginUrls());
        final BatchGenerateShortUrlResp resp = new BatchGenerateShortUrlResp();
        resp.setUrlInfoDTOs(urlInfoDTOs);

        return Result.ok(resp);
    }
}
